package com.itheima.interceptors;

import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取令牌
        String token = request.getHeader("Authorization");// Authorization为请求头的键
        // 验证令牌
        try {
            // 解析令牌：没有异常说明验证成功
            Map<String, Object> claims = JwtUtil.parseToken(token);
            String username = (String) claims.get("username");
            String redisToken = stringRedisTemplate.opsForValue().get(username);
            // 如果用户携带的token与redis中存储的该用户的token不一致，则不放行
            if(!token.equals(redisToken)) {
                throw new RuntimeException();
            }
            // 把用户信息存入ThreadLocal对象中
            UserHolder.set(claims);
            return true;// 放行
        } catch (Exception e) {
            // 出现异常说明验证失败
            response.setStatus(401);// 状态码改为401
            return false;// 不放行
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
